import re
from datetime import datetime, date

from django.contrib import admin, messages
from django import forms
from . import site
from .models import Upload, Report
import xlrd
from dateutil.relativedelta import relativedelta

from utils.timezone import tzinfo, gen_month_range
from .excel2db import MAPPER, SaveSheet
from .gen_report import bline_month_report, bdept_month_report


class UploadForm(forms.ModelForm):
    class Meta:
        model = Upload
        fields = ['file']

    def clean_file(self):
        value = self.cleaned_data['file']

        for k in MAPPER:
            tp = re.match(k, value.name)
            if tp:
                self.match_and_key = (tp, k)
                return value
        err_msg = "-or-".join(['<' + k.pattern +'>' for k in MAPPER.keys()])
        raise forms.ValidationError(f'文件名称必须符合：\n{err_msg}')


class ReportForm(forms.ModelForm):
    class Meta:
        model = Report
        fields = ['begin_month', 'end_month']

    def clean(self):
        begin_month = self.cleaned_data['begin_month']
        end_month = self.cleaned_data['end_month']

        if None in (begin_month, end_month):
            begin_month, end_month = gen_month_range()
            # 扔掉时区
            begin_month = date(year=begin_month.year, month=begin_month.month, day=1)
            end_month = date(year=end_month.year, month=end_month.month, day=1)

            self.cleaned_data['begin_month'] = begin_month
            self.cleaned_data['end_month'] = end_month
            return

        if begin_month.year == end_month.year:
            if begin_month.month >= end_month.month:
                raise forms.ValidationError('<开始月份> 必须小于 <结束月份>')
        elif begin_month.year > end_month.year:
            raise forms.ValidationError('<开始年份> 必须小于 <结束年份>')

        #  去除 day
        self.cleaned_data['begin_month'] = date(year=begin_month.year, month=begin_month.month, day=1)
        self.cleaned_data['end_month'] = date(year=end_month.year, month=end_month.month, day=1)


class ReportAdmin(admin.ModelAdmin):
    form = ReportForm

    def save_model(self, request, obj:Report, form, change):
        super(ReportAdmin, self).save_model(request, obj, form, change)
        begin_month = form.cleaned_data['begin_month']
        end_month = form.cleaned_data['end_month']

        # 找回时区
        begin_month = datetime(year=begin_month.year, month=begin_month.month, day=1, tzinfo=tzinfo)
        end_month = datetime(year=end_month.year, month=end_month.month, day=1, tzinfo=tzinfo)

        month_delta = relativedelta(months=1)

        month_lft = begin_month

        while month_lft < end_month:
            month_rht = month_lft + month_delta
            print('----->', month_lft, month_rht)
            bline_month_report(month_lft, month_rht)
            bdept_month_report(month_lft, month_rht)

            month_lft = month_rht


class UploadAdmin(admin.ModelAdmin):
    form = UploadForm

    def save_model(self, request, obj:Upload, form:UploadForm, change):
        super(UploadAdmin, self).save_model(request, obj, form, change)
        try:
            workbook = xlrd.open_workbook(obj.file.path)
            sheet = workbook.sheet_by_index(0)
            SaveSheet(sheet, form.match_and_key, workbook).save()

            self.message_user(request, '成功保存数据')
        except Exception as e:
            self.message_user(request, '失败{}'.format(e), level=messages.ERROR)


site.register(Upload, UploadAdmin)
site.register(Report, ReportAdmin)
